#region Using References

using System.IO;
using Beaker.Services.FileSystem;
using Ionic.Zip;

#endregion

namespace Beaker.OpenCube.Specs.Builders
{
	public class ZipStreamBuilder
		: Builder<Stream>
	{
		private IFolder _folder;

		public ZipStreamBuilder WithFilesFrom( IFolder folderWithFiles, bool includeFolderItself = false )
		{
			_folder = folderWithFiles;
			return this;
		}

		protected override Stream OnBuild()
		{
			var zipStream = new MemoryStream();
			using( var zipFile = new ZipFile() )
			{
				if( _folder != null )
				{
					MoveFiles( zipFile, _folder );
				}

				zipFile.Save( zipStream );
			}

			zipStream.Flush();
			zipStream.Position = 0;

			return zipStream;
		}

		private void MoveFiles( ZipFile zipFile, IFolder sourceFolder, string parentPath = "" )
		{
			var files = sourceFolder.GetFiles();

			foreach( IFile file in files )
			{
				var f = file;
				zipFile.AddEntry( Path.Combine( parentPath, file.Name ), n => f.OpenRead(), ( n, s ) => s.Close() );
			}

			foreach( IFolder folder in sourceFolder.GetFolders() )
			{
				MoveFiles( zipFile, folder, Path.Combine( parentPath, folder.Name ) );
			}
		}
	}
}